package com.netty.encodeDecode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年08月10日
 * @Description
 */
public class HttpNettyClient {

    public static void main(String[] args) throws InterruptedException {

        Bootstrap bootstrap = new Bootstrap();   //客户端也是使用Bootstrap来启动,但是不带server了
        bootstrap
                .group(new NioEventLoopGroup())   //客户端就没那么麻烦了，直接一个EventLoop就行，用于处理发回来的数据
                .channel(NioSocketChannel.class)   //客户端肯定就是使用SocketChannel了
                .handler(new ChannelInitializer<SocketChannel>() {   //这里的数据处理方式和服务端是一样的
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        // 配置流水线
                        channel.pipeline()
                                .addLast(new StringDecoder())
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(">> 接收到服务器端发回的数据：" + msg);
                                    }
                                })
                                .addLast(new StringEncoder());
                    }
                });

        Channel channel = bootstrap.connect("localhost", 8080).channel();
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                System.out.println("<< 请输入要发送给服务端的内容：");
                String text = scanner.nextLine();
                if (text.isEmpty()) {
                    continue;
                }
                channel.writeAndFlush(text);
            }
        }

    }
}

